﻿//------------------------------------------------------------------------------------------------- 
// <copyright file="UploadWorker.cs" company="Elpaulo Productions">
//   Copyright (c) Elpaulo Productions. All rights reserved.
// </copyright>
//-------------------------------------------------------------------------------------------------
namespace Elpaulo.Canardpc.CanardpcImageUploader
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Linq;
    using System.Text;

    using Elpaulo.Canardpc.TofCanardpcAPI;

    /// <summary>
    /// This class send a batch of images to tof.canardpc.com
    /// </summary>
    public class UploadWorker : BackgroundWorker
    {
        /// <summary>
        /// Image panels to process
        /// </summary>
        private List<ImagePanel> _imagePanels;

        /// <summary>
        /// Initializes a new instance of the UploadWorker class
        /// </summary>
        /// <param name="imagePanels">Images to upload</param>
        public UploadWorker(List<ImagePanel> imagePanels)
        {
            _imagePanels = imagePanels;

            this.WorkerReportsProgress = true;
            this.DoWork += new DoWorkEventHandler(UploadWorker_DoWork);
        }

        /// <summary>
        /// Processing of image panels
        /// </summary>
        /// <param name="sender">The UploadWorker</param>
        /// <param name="e">Event args</param>
        private void UploadWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            // Submit parameter
            NameValueCollection nameValueCollection = new NameValueCollection();
            nameValueCollection.Add(Properties.Settings.Default.SubmitFieldName, string.Empty);

            // Adding to queue
            _imagePanels.ForEach(imagePanel => imagePanel.ImageState = ImageState.Queued);

            foreach (ImagePanel imagePanel in _imagePanels)
            {
                imagePanel.ImageState = ImageState.Uploading;
                string urlLinkPage = TofCanardpcAPI.UploadImage(Properties.Settings.Default.URLTofCanarpcCom, imagePanel.LocalPath, Properties.Settings.Default.FileFieldName, "image/jpeg", nameValueCollection);
                ImageLinks links = TofCanardpcAPI.ExtractLinksFromUrl(urlLinkPage);
                imagePanel.FillLinkTextBoxes(links);
                imagePanel.ImageState = ImageState.Uploaded;
            }
        }
    }
}
